#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""域名证书相关操作类。

该类提供了获取域名证书等操作。 

Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import ssl
import socket
from typing import Optional, Dict, List

from wingman import logger
from wingman.common.error import ErrorCode
from wingman import epochExpire


class CustomSSL:
    """域名证书相关操作类。

    该类提供了获取域名证书等操作。
    """
    def get_cert(self, domain: str, host: Optional[str] = None, port: int = 443, timeout: int = 5) -> Dict[str, str]:
        """初始化SSL证书检查器。

        Args:
            domain (str): 要检查的域名
            host (Optional[str]): 目标主机IP，默认为None（使用域名）
            port (int): 端口号，默认为443
            timeout (int): 连接超时时间，默认为5秒

        Raises:
            ValueError: 如果domain参数为空或无效
        """
        host if host else domain

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            sock.connect((host, port))
            ssl_context = ssl.create_default_context()
            wrap_socket = ssl_context.wrap_socket(sock, server_hostname=domain)
            self.cert = wrap_socket.getpeercert()
            wrap_socket.close()
            return self.cert
        except Exception as e:
            logger.error(ErrorCode.SUCCESS.value, f"获取证书失败: {e}", __name__)
            return {}

    def get_cert_time(self, domain: str, host: Optional[str] = None, port: int = 443, timeout: int = 5) -> Dict[str, str]:
        """
        解析证书信息，仅解析重要信息

        Args:
            domain (str): 要检查的域名
            host (Optional[str]): 目标主机IP，默认为None（使用域名）
            port (int): 端口号，默认为443

        Returns:
            dict: 包含证书开始日期和过期日期的字典
        """
        self.get_cert(domain, host, port, timeout)
        data = {
            "domain": domain,
            "host": host,
            "port": port,
            "start_date": self.cert['notBefore'],
            "expire_date": self.cert['notAfter'],
            # "subject": cert['subject'],
            # "start_date": time_util.parse_time(cert['notBefore']),
            # "expire_date": time_util.parse_time(cert['notAfter']),
        }
        return data

    def get_cert_expire(self, domain: str, host: Optional[str] = None, port: int = 443, timeout: int = 5) -> str:
        """
        解析证书信息，仅解析重要信息

        Args:
            domain (str): 要检查的域名
            host (Optional[str]): 目标主机IP，默认为None（使用域名）
            port (int): 端口号，默认为443

        Returns:
            int: 到达过期日期的天数

        {'expire_date': 'Aug  9 01:41:01 2025 GMT'}
        """
        self.get_cert(domain, host, port, timeout)
        return epochExpire(self.cert['notAfter'])


if __name__ == '__main__':
    cert = CustomSSL()
    domain = 'www.baidu.com'
    ip = '220.181.111.232'
    port = 443
    # print(cert.get_cert(domain, ip))
    # print(cert.get_cert(domain, ip, port))
    # print(cert.get_cert_time(domain, ip, port))
    print(cert.get_cert_expire(domain, ip, port))
